package com.atbun.msmservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.atbun.msmservice.service.MsmService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Description : 发送短信服务方
 * @Author : mayp
 * @Date: 2020-05-15 08:40
 */
@Service
public class MsmServiceImpl implements MsmService {

    /**
     * 发送短信
     * @param PhoneNumbers
     * @param templateCode
     * @param param
     * @return
     */
    @Override
    public boolean send(String PhoneNumbers, String templateCode, Map<String, Object> param) {
//        如果手机号为空
        if (StringUtils.isEmpty(PhoneNumbers)){
            return false;
        }
//         区域编号，访问密钥id，AccessKey Secret与阿里云的密钥一致
        DefaultProfile profile = DefaultProfile.getProfile("default","LTAI4G6ECh4q4mekTuu3WQR1","R8IY0cSRPKByTe6kiYGddctCU8U8v1");
//        阿里云固定写法
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

//        PhoneNumbers手机号码。SignName 自己的签名管理的签名名称，TemplateCode 自己的阿里云模板管理CODE，TemplateParam验证码类型（6位）
        request.putQueryParameter("PhoneNumbers", PhoneNumbers);
        request.putQueryParameter("SignName", "我的包子在线教育网站");
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
